<template>
    <div>
        <!-- Basic Info -->
        <a-form-model :model="form" class="mqtt-config-form">
            <a-row :gutter="16">
                <a-col :span="12">
                    <a-form-model-item label="MQTT名称">
                        <a-tooltip title="请在MQTT管理中修改" placement="top">
                            <a-input 
                                v-model="form.name" 
                                :disabled="true"
                                style="cursor: not-allowed;"
                            />
                        </a-tooltip>
                    </a-form-model-item>
                </a-col>
                <a-col :span="12">
                    <a-row>
                        <a-col :span="12">
                            <a-form-model-item
                                label="网卡类型"
                                :label-col="{ span: 8 }"
                                :wrapper-col="{ span: 16 }"
                            >
                                <a-select v-model="form.cardType" @change="handleInputChange">
                                    <a-select-option
                                        v-for="option in cardTypeOptions"
                                        :key="option"
                                        :value="option"
                                    >
                                        {{ option }}
                                    </a-select-option>
                                </a-select>
                            </a-form-model-item>
                        </a-col>
                        <a-col :span="12">
                            <a-form-model-item
                                label="服务器类型"
                                :label-col="{ span: 10 }"
                                :wrapper-col="{ span: 14 }"
                            >
                                <a-select v-model="form.serverType" @change="handleInputChange">
                                    <a-select-option
                                        v-for="option in serverTypeOptions"
                                        :key="option"
                                        :value="option"
                                    >
                                        {{ option }}
                                    </a-select-option>
                                </a-select>
                            </a-form-model-item>
                        </a-col>
                    </a-row>
                </a-col>
            </a-row>
            <a-row :gutter="16">
                <a-col :span="12">
                    <a-form-model-item label="服务器地址">
                        <a-input v-model="form.address" @input="handleInputChange" />
                    </a-form-model-item>
                </a-col>
                <a-col :span="12">
                    <a-form-model-item label="服务器端口">
                        <a-input v-model="form.port" @input="handleInputChange" />
                    </a-form-model-item>
                </a-col>
            </a-row>
            <a-row :gutter="16">
                <a-col :span="12">
                    <a-form-model-item label="客户端ID">
                        <a-input v-model="form.clientId" @input="handleInputChange" />
                    </a-form-model-item>
                </a-col>
                <a-col :span="12">
                    <a-form-model-item label="用户名">
                        <a-input v-model="form.username" @input="handleInputChange" />
                    </a-form-model-item>
                </a-col>
            </a-row>
            <a-row :gutter="16">
                <a-col :span="12">
                    <a-form-model-item label="连接密钥">
                        <a-input
                            v-model="form.password"
                            @input="handleInputChange"
                        />
                    </a-form-model-item>
                </a-col>
                <a-col :span="12">
                    <a-form-model-item label="连接心跳">
                        <a-input v-model="form.keepalive" @input="handleInputChange" />
                    </a-form-model-item>
                </a-col>
            </a-row>
        </a-form-model>

        <!-- Topics -->
        <div class="topics-section">
            <!-- Publish Topics -->
            <a-divider orientation="left">发布主题</a-divider>
            <div class="topic-grid header">
                <span>启用主题</span>
                <span class="topic-content">主题内容</span>
                <span>QOS</span>
                <span>有效负载的格式</span>
                <span>主题类型</span>
                <span>主动上报数据时间间隔(s)</span>
            </div>
            <div
                v-for="item in form.publishTopics"
                :key="'pub-' + item.id"
                class="topic-grid"
            >
                <a-checkbox v-model="item.enabled" @change="handleInputChange" />
                <a-input v-model="item.content" @input="handleInputChange" />
                <a-select v-model="item.qos" @change="handleInputChange">
                    <a-select-option value="Qos0">Qos0</a-select-option>
                    <a-select-option value="Qos1">Qos1</a-select-option>
                    <a-select-option value="Qos2">Qos2</a-select-option>
                </a-select>
                <a-select v-model="item.payloadFormat" class="payload-format-select" :dropdown-style="getPayloadFormatDropdownStyle()" @change="handleInputChange">
                    <a-select-option
                        v-for="option in payloadFormatOptions"
                        :key="option"
                        :value="option"
                    >
                        {{ option }}
                    </a-select-option>
                </a-select>
                <a-select v-model="item.topicType" class="topic-type-select" :dropdown-style="getTopicTypeDropdownStyle()" @change="handleInputChange">
                    <a-select-option
                        v-for="option in topicTypeOptions"
                        :key="option"
                        :value="option"
                    >
                        {{ option }}
                    </a-select-option>
                </a-select>
                <a-input v-model="item.interval" @input="handleInputChange" />
            </div>

            <!-- Subscribe Topics -->
            <a-divider orientation="left">订阅主题</a-divider>
            <div class="topic-grid header">
                <span>启用主题</span>
                <span class="topic-content">主题内容</span>
                <span>QOS</span>
                <span>有效负载的格式</span>
                <span>主题类型</span>
                <span />
            </div>
            <div
                v-for="item in form.subscribeTopics"
                :key="'sub-' + item.id"
                class="topic-grid"
            >
                <a-checkbox v-model="item.enabled" @change="handleInputChange" />
                <a-input v-model="item.content" @input="handleInputChange" />
                <a-select v-model="item.qos" @change="handleInputChange">
                    <a-select-option value="Qos0">Qos0</a-select-option>
                    <a-select-option value="Qos1">Qos1</a-select-option>
                    <a-select-option value="Qos2">Qos2</a-select-option>
                </a-select>
                <a-select v-model="item.payloadFormat" class="payload-format-select" :dropdown-style="getPayloadFormatDropdownStyle()" @change="handleInputChange">
                    <a-select-option
                        v-for="option in payloadFormatOptions"
                        :key="option"
                        :value="option"
                    >
                        {{ option }}
                    </a-select-option>
                </a-select>
                <a-select v-model="item.topicType" class="topic-type-select" :dropdown-style="getTopicTypeDropdownStyle()" @change="handleInputChange">
                    <a-select-option
                        v-for="option in topicTypeOptions"
                        :key="option"
                        :value="option"
                    >
                        {{ option }}
                    </a-select-option>
                </a-select>
                <span />
            </div>
        </div>

        <!-- SSL Configuration -->
        <div v-if="form.securityLayer === 'ssl'" class="ssl-config-section">
            <a-divider orientation="left">SSL配置</a-divider>
            <a-row :gutter="16">
                <a-col :span="24">
                    <a-form-model-item label="SSL文件类型">
                        <div class="ssl-file-config">
                            <div class="ssl-file-item">
                                <div class="ssl-file-label">
                                    <a-radio 
                                        :checked="form.sslFileType === 'CAFile'" 
                                        value="CAFile" 
                                        @change="handleSslTypeChange"
                                    >
                                        <span>CAFile</span>
                                        <span style="margin-left: 8px; color: #666;">SSL根证书文件</span>
                                    </a-radio>
                                </div>
                                <div class="ssl-file-input">
                                    <a-input 
                                        v-model="form.cafile" 
                                        placeholder="请选择CAFile文件路径"
                                        :disabled="form.sslFileType !== 'CAFile'"
                                        @input="handleInputChange" 
                                    />
                                    <a-button 
                                        :disabled="form.sslFileType !== 'CAFile'"
                                        @click="selectSslFile('CAFile')"
                                    >
                                        ...
                                    </a-button>
                                </div>
                            </div>
                                
                            <div class="ssl-file-item">
                                <div class="ssl-file-label">
                                    <a-radio 
                                        :checked="form.sslFileType === 'CertFile'" 
                                        value="CertFile" 
                                        @change="handleSslTypeChange"
                                    >
                                        <span>CertFile</span>
                                        <span style="margin-left: 8px; color: #666;">SSL客户端证书文件</span>
                                    </a-radio>
                                </div>
                                <div class="ssl-file-input">
                                    <a-input 
                                        v-model="form.certfile" 
                                        placeholder="请选择CertFile文件路径"
                                        :disabled="form.sslFileType !== 'CertFile'"
                                        @input="handleInputChange" 
                                    />
                                    <a-button 
                                        :disabled="form.sslFileType !== 'CertFile'"
                                        @click="selectSslFile('CertFile')"
                                    >
                                        ...
                                    </a-button>
                                </div>
                            </div>
                                
                            <div class="ssl-file-item">
                                <div class="ssl-file-label">
                                    <a-radio 
                                        :checked="form.sslFileType === 'KeyFile'" 
                                        value="KeyFile" 
                                        @change="handleSslTypeChange"
                                    >
                                        <span>KeyFile</span>
                                        <span style="margin-left: 8px; color: #666;">SSL客户端私钥文件</span>
                                    </a-radio>
                                </div>
                                <div class="ssl-file-input">
                                    <a-input 
                                        v-model="form.keyfile" 
                                        placeholder="请选择KeyFile文件路径"
                                        :disabled="form.sslFileType !== 'KeyFile'"
                                        @input="handleInputChange" 
                                    />
                                    <a-button 
                                        :disabled="form.sslFileType !== 'KeyFile'"
                                        @click="selectSslFile('KeyFile')"
                                    >
                                        ...
                                    </a-button>
                                </div>
                            </div>
                        </div>
                    </a-form-model-item>
                </a-col>
            </a-row>
        </div>

        <!-- Bottom Controls -->
        <a-row
            :gutter="16"
            type="flex"
            justify="space-between"
            align="middle"
            style="margin-top: 16px;"
        >
            <a-col :span="24">
                <a-form-model-item
                    label="选择层安全"
                    :label-col="{ span: 4 }"
                    :wrapper-col="{ span: 20 }"
                >
                    <div style="display: flex; align-items: center;">
                        <a-select
                            v-model="form.securityLayer"
                            style="min-width: 120px; max-width: 180px; margin-right: 24px;"
                            @change="handleInputChange"
                        >
                            <a-select-option value="null">null</a-select-option>
                            <a-select-option value="ssl">ssl</a-select-option>
                        </a-select>
                        <a-checkbox
                            v-model="form.clearSession"
                            style="margin-right: 24px;"
                            @change="handleInputChange"
                        >
                            清除回话
                        </a-checkbox>
                        <a-checkbox v-model="form.startTls" @change="handleInputChange">
                            是否开启连接
                        </a-checkbox>
                    </div>
                </a-form-model-item>
            </a-col>
            <a-col :span="24">
                <div style="text-align: right;">
                    <a-button style="margin-right: 8px;" @click="showAliKeyDialog">阿里云密钥计算</a-button>
                    <a-button type="primary" @click="$emit('save')">保存配置</a-button>
                </div>
            </a-col>
        </a-row>

        <!-- 阿里云密钥计算对话框 -->
        <ali-key-dialog
            :visible="aliKeyDialogVisible"
            :ali-cloud-type-options="aliCloudTypeOptions"
            @ok="handleAliKeyOk"
            @cancel="handleAliKeyCancel"
        />
    </div>
</template>

<script>
import AliKeyDialog from './components/AliKeyDialog.vue'
import { openFileDialog } from '@/api/TabAxios/base'

export default {
    name: 'MqttConfig',
    components: {
        AliKeyDialog
    },
    props: {
        value: {
            type: Object,
            required: true
        },
        dbId: {
            type: [Number, String],
            required: false,
            default: null
        },
        cardTypeOptions: {
            type: Array,
            default: () => []
        },
        serverTypeOptions: {
            type: Array,
            default: () => []
        },
        topicTypeOptions: {
            type: Array,
            default: () => []
        },
        payloadFormatOptions: {
            type: Array,
            default: () => []
        },
        aliCloudTypeOptions: {
            type: Array,
            default: () => []
        }
    },
    data() {
        return {
            form: this.initializeForm(this.value),
            isUpdating: false, // 防止循环更新的标志
            aliKeyDialogVisible: false,
            aliKeyForm: {
                region: this.aliCloudTypeOptions.length > 0 ? this.aliCloudTypeOptions[0] : '华东',
                domain: '',
                deviceName: '',
                productKey: '',
                deviceSecret: '',
                timeStamp: '',
                connectionKey: ''
            }
        }
    },
    watch: {
        value: {
            handler(newValue) {
                if (!this.isUpdating) {
                    this.form = this.initializeForm(newValue)
                }
            },
            immediate: false
        },
        // 监听选项数组的变化
        cardTypeOptions: {
            handler(newOptions) {
                console.log('🔄 [MqttConfig] cardTypeOptions更新:', newOptions)
                this.updateFormWithNewOptions()
            },
            immediate: true
        },
        serverTypeOptions: {
            handler(newOptions) {
                console.log('🔄 [MqttConfig] serverTypeOptions更新:', newOptions)
                this.updateFormWithNewOptions()
            },
            immediate: true
        },
        topicTypeOptions: {
            handler(newOptions) {
                console.log('🔄 [MqttConfig] topicTypeOptions更新:', newOptions)
                this.updateFormWithNewOptions()
            },
            immediate: true
        },
        payloadFormatOptions: {
            handler(newOptions) {
                console.log('🔄 [MqttConfig] payloadFormatOptions更新:', newOptions)
                // 当选项更新时，更新表单中的默认值
                this.updateFormWithNewOptions()
            },
            immediate: true
        },
        aliCloudTypeOptions: {
            handler(newOptions) {
                console.log('🔄 [MqttConfig] aliCloudTypeOptions更新:', newOptions)
            },
            immediate: true
        }
    },
    created() {
        // 创建防抖的更新函数
        this.debouncedEmit = this.debounce(this.emitChange, 300)
    },
    methods: {
        // 简单的防抖函数
        debounce(func, delay) {
            let timeoutId
            return function(...args) {
                clearTimeout(timeoutId)
                timeoutId = setTimeout(() => func.apply(this, args), delay)
            }
        },

        // 初始化表单数据
        initializeForm(value) {
            console.log('🔄 [MqttConfig] initializeForm:', value)

            return {
                name: value.name || 'name',
                address: value.address || '127.0.0.1',
                port: value.port || '1883',
                clientId: value.clientId || 'clientId',
                username: value.username || 'userName',
                password: value.password || 'password',
                keepalive: value.keepalive || 60,
                cardType: value.cardType || this.cardTypeOptions.length > 0 ? this.cardTypeOptions[0] : '',
                serverType: value.serverType || this.serverTypeOptions.length > 0 ? this.serverTypeOptions[0] : '',
                publishTopics: this.initializeTopics(value.publishTopics, 5),
                subscribeTopics: this.initializeTopics(value.subscribeTopics, 5),
                securityLayer: value.securityLayer || 'null',
                clearSession: value.clearSession || false,
                startTls: value.startTls || false,
                sslFileType: value.sslFileType || 'CAFile',
                cafile: value.cafile || '',
                certfile: value.certfile || '',
                keyfile: value.keyfile || ''
            }
        },

        // 初始化主题数据
        initializeTopics(topics, defaultCount) {
            // 如果有数据，按照原始顺序创建
            if (Array.isArray(topics) && topics.length > 0) {
                return topics.map((topic, index) => {
                    const payloadFormat = topic.payloadFormat || (this.payloadFormatOptions.length > 0 ? this.payloadFormatOptions[0] : '')
                    const topicType = topic.topicType || (this.topicTypeOptions.length > 0 ? this.topicTypeOptions[0] : '')
                    return {
                        id: topic.id || index + 1,
                        content: topic.content || '',
                        qos: topic.qos || 'Qos0',
                        enabled: topic.enabled || false,
                        payloadFormat: payloadFormat,
                        interval: topic.interval || 30,
                        topicType: topicType
                    }
                })
            }
            // 如果没有数据，创建默认数量的空主题，保持顺序
            return Array.from({ length: defaultCount }, (_, index) => ({
                id: index + 1,
                content: '',
                qos: 'Qos0',
                enabled: false,
                payloadFormat: this.payloadFormatOptions.length > 0 ? this.payloadFormatOptions[0] : '',
                interval: 30,
                topicType: this.topicTypeOptions.length > 0 ? this.topicTypeOptions[0] : ''
            }))
        },
        // 处理输入变化
        handleInputChange() {
            this.debouncedEmit()
        },

        // 发送变化事件
        emitChange() {
            this.isUpdating = true
            this.$emit('input', { ...this.form })
            this.$nextTick(() => {
                this.isUpdating = false
            })
        },

        // 当选项数组更新时，更新表单中的默认值
        updateFormWithNewOptions() {
            if (this.isUpdating) return // 防止循环更新
            
            console.log('🔄 [MqttConfig] 更新表单选项:', {
                cardTypeOptions: this.cardTypeOptions,
                serverTypeOptions: this.serverTypeOptions,
                payloadFormatOptions: this.payloadFormatOptions,
                topicTypeOptions: this.topicTypeOptions
            })

            // 更新表单中的默认选项
            if (this.cardTypeOptions.length > 0 && !this.form.cardType) {
                this.form.cardType = this.cardTypeOptions[0]
            }
            if (this.serverTypeOptions.length > 0 && !this.form.serverType) {
                this.form.serverType = this.serverTypeOptions[0]
            }

            // 更新主题中的默认选项
            const updateTopicDefaults = topics => {
                if (!Array.isArray(topics)) return
                
                topics.forEach(topic => {
                    // 只有当payloadFormat为空字符串或undefined时才设置默认值
                    if (this.payloadFormatOptions.length > 0 && (!topic.payloadFormat || topic.payloadFormat === '')) {
                        topic.payloadFormat = this.payloadFormatOptions[0]
                    }
                    // 只有当topicType为空字符串或undefined时才设置默认值
                    if (this.topicTypeOptions.length > 0 && (!topic.topicType || topic.topicType === '')) {
                        topic.topicType = this.topicTypeOptions[0]
                    }
                })
            }

            updateTopicDefaults(this.form.publishTopics)
            updateTopicDefaults(this.form.subscribeTopics)
        },

        showAliKeyDialog() {
            this.aliKeyDialogVisible = true
        },
        handleAliKeyOk(formData) {
            this.aliKeyForm = { ...formData }
            this.aliKeyDialogVisible = false
            
            // 更新 MqttConfig 中的相关字段
            if (formData.domain) {
                this.form.address = formData.domain
            }
            if (formData.mqttClientId) {
                this.form.clientId = formData.mqttClientId
            }
            if (formData.mqttUserName) {
                this.form.username = formData.mqttUserName
            }
            if (formData.mqttPassword) {
                this.form.password = formData.mqttPassword
            }
            
            // 触发变化事件
            this.emitChange()
            
            // 显示成功提示
            this.$message.success('已成功更新服务器地址、客户端ID和用户名')
        },
        handleAliKeyCancel() {
            this.aliKeyDialogVisible = false
        },
        
        // 计算下拉菜单宽度
        calculateDropdownWidth(options) {
            if (!options || options.length === 0) return { minWidth: '150px' }
            
            // 创建临时元素来测量文本宽度
            const tempDiv = document.createElement('div')
            tempDiv.style.position = 'absolute'
            tempDiv.style.visibility = 'hidden'
            tempDiv.style.whiteSpace = 'nowrap'
            tempDiv.style.fontSize = '14px'
            tempDiv.style.fontFamily = '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif'
            tempDiv.style.padding = '8px 12px'
            document.body.appendChild(tempDiv)
            
            let maxWidth = 0
            options.forEach(option => {
                tempDiv.textContent = option
                const width = tempDiv.offsetWidth
                maxWidth = Math.max(maxWidth, width)
            })
            
            document.body.removeChild(tempDiv)
            
            // 添加一些额外空间
            const finalWidth = Math.max(maxWidth + 20, 150)
            return { minWidth: `${finalWidth}px` }
        },
        
        // 获取有效负载格式下拉菜单样式
        getPayloadFormatDropdownStyle() {
            return this.calculateDropdownWidth(this.payloadFormatOptions)
        },
        
        // 获取主题类型下拉菜单样式
        getTopicTypeDropdownStyle() {
            return this.calculateDropdownWidth(this.topicTypeOptions)
        },

        // 处理SSL文件类型变化
        handleSslTypeChange(e) {
            this.form.sslFileType = e.target.value
            this.handleInputChange()
        },

        // 选择SSL文件
        async selectSslFile(fileType) {
            try {
                // 根据文件类型设置文件过滤器
                const fileTypes = {
                    CAFile: 'SSL根证书文件 (*.crt;*.pem;*.cer)|*.crt;*.pem;*.cer|所有文件 (*.*)|*.*',
                    CertFile: 'SSL客户端证书文件 (*.crt;*.pem;*.cer)|*.crt;*.pem;*.cer|所有文件 (*.*)|*.*',
                    KeyFile: 'SSL客户端私钥文件 (*.key;*.pem)|*.key;*.pem|所有文件 (*.*)|*.*'
                }
                
                const fileFilter = fileTypes[fileType] || '所有文件 (*.*)|*.*'
                
                console.log(`🔍 [MqttConfig] 选择${fileType}文件，过滤器: ${fileFilter}`)
                
                const result = await openFileDialog({
                    title: `选择${fileType}文件`,
                    filter: fileFilter,
                    defaultExt: fileType === 'KeyFile' ? '.key' : '.crt'
                })
                
                if (result && result.data) {
                    const data = JSON.parse(result.data)
                    // 根据文件类型更新对应的字段
                    if (fileType === 'CAFile') {
                        this.form.cafile = data.filePath
                    } else if (fileType === 'CertFile') {
                        this.form.certfile = data.filePath
                    } else if (fileType === 'KeyFile') {
                        this.form.keyfile = data.filePath
                    }
                    
                    this.handleInputChange()
                    this.$message.success(`已选择${fileType}文件: ${data.filePath}`)
                }
            } catch (error) {
                console.error('❌ [MqttConfig] 选择SSL文件失败:', error)
                this.$message.error('选择文件失败: ' + error.message)
            }
        }
    }
}
</script>

<style scoped>
.mqtt-config-form .ant-form-item {
    display: flex;
    margin-bottom: 0;
}
.mqtt-config-form >>> .ant-form-item-label {
    width: 100px;
}
.mqtt-config-form >>> .ant-form-item-control-wrapper {
    flex: 1;
}
.topics-section {
    margin-top: 24px;
}
.topic-grid {
    display: grid;
    grid-template-columns: 80px 1fr 90px 150px 150px 100px;
    gap: 8px;
    align-items: center;
    margin-bottom: 8px;
}
.topic-grid.header {
    font-weight: bold;
    margin-bottom: 12px;
}
.topic-grid.header span {
    text-align: center;
    padding: 8px 4px;
    background: #f5f5f5;
    border: 1px solid #d9d9d9;
}
.topic-name {
    min-width: 100px;
}
.topic-content {
    text-align: center;
}

/* 只让启用主题（第1列）checkbox居中 */
.topic-grid > :nth-child(1),
.topic-grid > :nth-child(1) .ant-checkbox-wrapper {
    display: flex !important;
    justify-content: center !important;
    align-items: center !important;
}

/* SSL配置样式 */
.ssl-config-section {
    margin-top: 24px;
    padding: 16px;
}

/* SSL文件配置容器 */
.ssl-file-config {
    display: flex;
    flex-direction: column;
    gap: 16px;
}

/* SSL文件项 */
.ssl-file-item {
    display: flex;
    flex-direction: column;
    gap: 8px;
    padding: 12px;
    border: 1px solid #d9d9d9;
    border-radius: 4px;
    background-color: white;
    opacity: 0.85;
    transition: opacity 0.3s;
}
.ssl-file-item:has(.ant-radio-wrapper-checked) {
    opacity: 1;
}

/* SSL文件标签区域 */
.ssl-file-label {
    display: flex;
    align-items: center;
}
.ssl-file-label .ant-radio-wrapper {
    margin: 0;
}

/* SSL文件输入区域 */
.ssl-file-input {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-left: 24px; /* 与radio按钮对齐 */
}
.ssl-file-input .ant-input {
    flex: 1;
}
.ssl-file-input .ant-btn {
    padding: 4px 8px;
    min-width: 40px;
}

/* 禁用状态样式 */
.ssl-file-input .ant-input[disabled] {
    background-color: #f5f5f5;
    cursor: not-allowed;
}
</style> 